import axios from 'axios'
import { Notification, Message, MessageBox, Loading } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { tansParams, blobValidate } from "@/utils/nami";
import { saveAs } from 'file-saver'
import errorCode from '@/utils/errorCode'

let downloadLoadingInstance;

// 是否显示重新登录
export let isRelogin = { show: false };

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

// 创建一个axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时时间
  timeout: 5000
})

// request拦截器
service.interceptors.request.use(
  config => {
    // 是否需要防止数据重复提交
    const isRepeatSubmit = (config.headers || {}).repeatSubmit === false
    if (store.getters.token) {
      config.headers['Authorization'] = 'Nami-' + getToken()
    }
    // get delete 请求映射params参数
    if ((config.method === 'get' || config.method === 'delete') && config.params) {
      let url = config.url + '?' + tansParams(config.params);
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }
    if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
      config.data = typeof config.data === 'object' ? JSON.stringify(config.data) : config.data
    }
    return config
  },
  error => {
    // 请求出错时处理
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // 未设置状态码则默认成功状态
    const code = response.data.code || 200;
    // 获取错误信息
    const message = errorCode[code] || response.data.message || errorCode['default']
    // 二进制数据则直接返回
    if(response.request.responseType ===  'blob' || response.request.responseType ===  'arraybuffer'){
      return response.data
    }
    const res = response.data
    // 如果自定义代码不是200，则判定为错误。
    if (res.code !== 200) {
      // 401:令牌过期;403:无权限
      if (res.code === 401) {
        console.log("isRelogin", isRelogin)
        if (!isRelogin.show) {
          isRelogin.show = true;
          MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            store.dispatch('user/logout').then(() => {
              location.href = '/index';
            })
          }).catch(() => {
            isRelogin.show = false;
          });
        }
        return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
      } else if (code === 500) {
        Message({ message: message, type: 'error' })
        return Promise.reject(new Error(message))
      } else {
        Notification.error({ title: message })
        Message({ message: "未知错误,请联系管理员!", type: 'error' })
        return Promise.reject('error')
      }
    } else {
      return res.data
    }
  },
  error => {
    console.log('err' + error)
    let { message } = error;
    if (message === "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    } else {
      message = "未知异常,请联系管理员";
    }
    console.log(message)
    Message({
      message: message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export function download(url, params, filename, config) {
  downloadLoadingInstance = Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
  const queryParams = tansParams(params)
  return service.post(url, params, {
    transformRequest: [() => { return queryParams }],
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'blob',
    ...config
  }).then(async (data) => {
    const isLogin = await blobValidate(data);
    console.log("isLogin", isLogin)
    if (isLogin) {
      const blob = new Blob([data])
      saveAs(blob, filename)
    } else {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
      Message.error(errMsg);
    }
    downloadLoadingInstance.close();
  }).catch(() => {
    Message.error('下载文件出现错误，请联系管理员！')
    downloadLoadingInstance.close();
  })
}

export default service
